import type { TooltipProps } from 'antd';
import { isArray, isObject } from 'lodash';
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { ITextBasicProps } from '.';
import { CustomTooltip } from '../CustomTooltip';
import styles from './typography.module.less';

const TextLayout = styled.div`
  display: -webkit-box;
  -webkit-line-clamp: inherit; // 由React组件动态传入
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
`;

interface Props extends ITextBasicProps {
  /** 行数，默认2行，溢出省略号 */ lines?: number;
  /** 是否隐藏提示 */ hideTooltip?: boolean;
  /** antd框架Tooltip组件属性 */ tooltipProps?: TooltipProps;
  /** 和text二选一 */ text?: React.ReactNode;
}

const Text: React.FC<Props> = (props) => {
  const {
    text,
    lines = 1,
    className,
    style,
    onClick,
    children,
    hideTooltip,
    tooltipProps,
  } = props;

  const textStr = text || children;

  if (isArray(children)) {
    (children as any).map((v: any) => {
      if (isObject(v)) {
        // console.log(v, v.toString(), String(v));
      }
    });
  }
  const textRef = useRef<HTMLDivElement>(null);
  const [isOverflow, setIsOverflow] = useState(false);

  useEffect(() => {
    if (textRef.current) {
      setIsOverflow(
        textRef.current.scrollHeight > textRef.current.offsetHeight ||
          textRef.current.scrollWidth > textRef.current.offsetWidth,
      );
    }
  }, [textStr]);

  return (
    <>
      <CustomTooltip
        {...tooltipProps}
        title={!hideTooltip && isOverflow ? textStr : null}>
        <TextLayout
          ref={textRef}
          onClick={onClick}
          className={[
            `${styles.text}`,
            isOverflow ? `${styles['text-ellipsis']}` : '',
            className,
          ].join(' ')}
          style={{
            ...style,
            WebkitLineClamp: lines,
          }}>
          {textStr}
        </TextLayout>
      </CustomTooltip>
    </>
  );
};

export default Text;
